package com.meihua.workflow.exception;

import cn.hutool.core.bean.BeanUtil;

import com.meihua.workflow.constants.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import org.springframework.context.support.DefaultMessageSourceResolvable;

import javax.validation.ConstraintViolationException;
import javax.validation.ConstraintViolation;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


//设置异常捕获器
//全局异常处理
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {



    @ExceptionHandler({BizException.class})
    public R customException(BizException e ) {
        log.info(e.getMessage());
        return R.error(e.getMessage());

    }
//    请求参数异常



        //处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常
        @ExceptionHandler(BindException.class)
        @ResponseBody
        public R BindExceptionHandler(BindException e) {
            String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
            return R.error(message);
        }

        //处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是javax.validation.ConstraintViolationException
        @ExceptionHandler(ConstraintViolationException.class)

        public R ConstraintViolationExceptionHandler(ConstraintViolationException e) {
            String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
            return R.error(message);
        }

        //处理请求参数格式错误 @RequestBody上validate失败后抛出的异常是MethodArgumentNotValidException异常。
        @ExceptionHandler(MethodArgumentNotValidException.class)

        public R MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
            String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList()).toString();
            return R.error(message);
        }
}
